package com.moore.service.impl;

import com.moore.bean.Candidate;
import com.moore.bean.Comment;
import com.moore.mapper.CandidateMapper;
import com.moore.mapper.CommentMapper;
import com.moore.mapper.CommunityMapper;
import com.moore.mapper.LikeMapper;
import com.moore.service.CommentService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CandidateMapper candidateMapper;
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CommunityMapper communityMapper;

    @Override
    public List<Comment> getCommentList(Long communityId,Long candidateId) {
        List<Comment> commentList = commentMapper.getCommentsByCommunityId(communityId);
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        commentList.forEach(comment -> {
            Candidate candidate = candidateMapper.selectById(comment.getCandidateId());
            candidate.setCandidateImg(baseUrl + candidate.getCandidateImg());
            comment.setCandidate(candidate);
            comment.setIsLiked(likeMapper.existsByCommunityIdAndCommentIdAndCandidateId(communityId,comment.getCommentId(),candidateId));
        });
        return commentList;
    }

    @Override
    public int addComment(Comment comment) {
        int result = commentMapper.insertComment(comment);
        if (result > 0) {
            communityMapper.addCommentCount(comment.getCommunityId());
            return result;
        } else return 0;
    }

    @Override
    public int deleteComment(Long commentId, Long communityId) {
        int result = commentMapper.deleteComment(commentId);
        if (result > 0) {
            communityMapper.reduceCommentCount(communityId);
            return result;
        } else return 0;
    }

}
